﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Transactions;

namespace _17_ActionFilter
{
    /// <summary>
    /// 事务过滤器
    /// </summary>
    public class TransactionScopeFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // context.ActionDescriptor 当前被执行方法的描述信息
            // context.ActionArguments 当前被执行方法的参数信息
            ControllerActionDescriptor ctrlActionDesc = context.ActionDescriptor as ControllerActionDescriptor;
            bool isTX = false;
            if (ctrlActionDesc != null) //==null 不是一个MVC控制
            {
                // 判断是否标注NotTransationAttribute
                bool hasNotTransationAttribute = ctrlActionDesc.MethodInfo.GetCustomAttributes(typeof(NotTransationAttribute), false).Any();
                isTX=!hasNotTransationAttribute;
            }
            if (isTX)
            {
                using (TransactionScope tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    Console.WriteLine("开启事务...");
                    var r = await next(); //执行方法
                    if (r.Exception == null)
                    {
                        tx.Complete();
                        Console.WriteLine("提交事务...");
                    }
                }
            }
            else {
                await next();
            }

        }
    }
}
